<script setup lang="ts">
import { ref, reactive, onMounted, h, onBeforeUnmount } from 'vue'
const isMounted = ref(false)

onMounted(() => {
  isMounted.value = true
  fetchUserList()
})

onBeforeUnmount(() => {
  isMounted.value = false
})

import {
  Table as ATable,
  Card as ACard,
  Button as AButton,
  Input as AInput,
  Modal as AModal,
  Form as AForm,
  message,
  Popconfirm as APopconfirm,
  type TablePaginationConfig,
  Avatar as AAvatar,
  Upload
} from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { PlusOutlined, SearchOutlined } from '@ant-design/icons-vue'
import type { FormInstance, TableColumnsType, UploadChangeParam, UploadProps } from 'ant-design-vue'
import {
  addUser,
  getUserList,
  editUser,
  uploadAvatar,
  deleteUser,
  resetUserPassword
} from '../api/manger'

interface UserData {
  id: number
  userAccount: string
  phone: string
  email: string
  status: number
  gender: number
  createTime: string
  userRole: number
  username: string
  avatar?: string
  userStatus: number
}

interface UserForm {
  id?: number
  userAccount: string
  username: string
  avatar?: string
  phone: string
  email: string
  gender?: 0 | 1
  userStatus?: 0 | 1
  userRole?: 0 | 1
  userPassword?: string
  confirmPassword?: string
}

interface Pagination {
  total: number
  page: number
  size: number
}
const generateRandomUsername = (): string => {
  // 形容词列表
  const adjectives = [
    'Happy',
    'Clever',
    'Brave',
    'Gentle',
    'Jolly',
    'Kind',
    'Lucky',
    'Mystic',
    'Noble',
    'Quick'
  ]
  // 名词列表
  const nouns = [
    'Lion',
    'Tiger',
    'Eagle',
    'Dolphin',
    'Wolf',
    'Fox',
    'Bear',
    'Hawk',
    'Owl',
    'Falcon'
  ]

  // 随机选择形容词和名词
  const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)]
  const randomNoun = nouns[Math.floor(Math.random() * nouns.length)]

  // 组合成用户名并添加随机数字
  return `${randomAdjective}${randomNoun}${Math.floor(Math.random() * 100)}`
}
interface UserData {
  id: number
  userAccount: string
  phone: string
  email: string
  status: number
  gender: number
  createTime: string
  userRole: number
  username: string
  avatar?: string
  userStatus: number
}

interface UserForm {
  id?: number
  userAccount: string
  username: string
  avatar?: string
  phone: string
  email: string
  gender?: 0 | 1
  userStatus?: 0 | 1
  userRole?: 0 | 1
  userPassword?: string
  confirmPassword?: string
}

interface Pagination {
  total: number
  page: number
  size: number
}

// 关键修复1：添加组件卸载状态检查
const isComponentMounted = ref(true)
onBeforeUnmount(() => {
  isComponentMounted.value = false
})

// 关键修复2：兼容多种管理员角色标识
const isAdmin = ref(['0', 'admin'].includes(localStorage.getItem('userRole') || ''))

// 添加监听localStorage变化的逻辑
window.addEventListener('storage', () => {
  isAdmin.value = ['0', 'admin'].includes(localStorage.getItem('userRole') || '')
})

const searchForm = reactive({
  keyword: ''
})

const userForm = reactive<UserForm>({
  userAccount: '',
  username: '',
  avatar: '',
  phone: '',
  email: '',
  gender: 0,
  userStatus: 0,
  userRole: 1,
  userPassword: '',
  confirmPassword: ''
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('新增用户')
const isEdit = ref(false)

// 文件列表状态
const fileList = ref<unknown[]>([])

// 上传前校验
const beforeUpload: UploadProps['beforeUpload'] = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2 // 定义变量
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
  }
  // const isL极速学习法
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
  }
  return
}

// 处理上传变化
const handleChange = async (info: UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    loading.value = true
    return
  }

  if (info.file.status === 'done') {
    // 获取上传后的URL
    const { response } = info.file
    if (response.code === 200) {
      userForm.avatar = response.data
      message.success('头像上传成功')
    } else {
      message.error('头像上传失败')
    }
    loading.value = false
  } else if (info.file.status === 'error') {
    loading.value = false
    message.error('头像上传失败')
  }
}

// 自定义上传方法
const customRequest = async ({ file, onSuccess, onError }: any) => {
  try {
    const res = await uploadAvatar(file)
    onSuccess(res.data)
  } catch (error) {
    onError(error)
  }
}

// 添加头像生成函数
const generateAvatarColor = (userAccount: number) => {
  const hue = (userAccount * 137.5) % 360 // 使用黄金角确保颜色分布均匀
  return `hsl(${hue}, 70%, 60%)` // 保持明亮饱和的颜色
}

const generateInitialsAvatar = (username, userAccount) => {
  // 添加空值检查
  if (!username) {
    username = generateRandomUsername()
    return {
      text: username[0],
      backgroundColor: '#99cccc'
    }
  }

  const initials =
    username.trim().length > 0
      ? username
          .trim()
          .match(/\b(\w)/gu)
          ?.slice(0, 2)
          .join('')
      : 'U'

  return {
    text: initials ? initials.toUpperCase() : '',
    backgroundColor: generateAvatarColor(userAccount)
  }
}

const columns: TableColumnsType = [
  {
    title: '账号',
    dataIndex: 'userAccount',
    width: 150
  },
  {
    title: '用户名',
    dataIndex: 'username',
    width: 100
  },
  {
    title: '头像',
    dataIndex: 'avatar',
    width: 100,
    customRender: ({ record }) => {
      if (record.avatar) {
        return h(AAvatar, {
          src: record.avatar,
          size: 40
        })
      }

      const avatarData = generateInitialsAvatar(record.username, record.id)

      return h(
        'div',
        {
          style: {
            width: '40px',
            height: '40px',
            borderRadius: '50%',
            backgroundColor: avatarData.backgroundColor,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'green',
            fontWeight: 'bold',
            fontSize: '16px',
            boxShadow: '0 2px 5px rgba(0,0,0,0.15)'
          }
        },
        avatarData.text
      )
    }
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    width: 150
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'userStatus',
    width: 100,
    customRender: ({ text }) => (text === 1 ? '禁用' : '启用')
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 80,
    customRender: ({ text }) => {
      return text === 0 ? '男' : text === 1 ? '女' : '未知'
    }
  },
  {
    title: '角色',
    dataIndex: 'userRole',
    width: 100,
    customRender: ({ text }) => {
      return text === 0 ? '管理员' : '普通用户'
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
    customRender: ({ text }) => {
      return new Date(text).toLocaleString()
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    customRender: ({ record }) => {
      const handleEditClick = () => handleEdit(record as UserData)
      const handleResetClick = () => handleResetPassword((record as UserData).id)
      const handleDeleteClick = () => handleDelete((record as UserData).id)

      return h('div', { class: 'table-actions' }, [
        h(
          AButton,
          {
            type: 'link',
            onClick: handleEditClick
          },
          () => '编辑'
        ),
        h(
          APopconfirm,
          {
            title: '确定要重置密码吗？',
            onConfirm: handleResetClick
          },
          {
            default: () =>
              h(
                AButton,
                {
                  type: 'link'
                },
                () => '重置密码'
              )
          }
        ),
        h(
          APopconfirm,
          {
            title: '确定要删除该用户吗？',
            onConfirm: handleDeleteClick
          },
          {
            default: () =>
              h(
                AButton,
                {
                  type: 'link',
                  danger: true
                },
                () => '删除'
              )
          }
        )
      ])
    }
  }
]

const dataSource = ref<UserData[]>([])
const pagination = reactive<Pagination>({
  total: 0,
  page: 1,
  size: 10
})

const rules: Record<string, Rule[]> = {
  userAccount: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, message: '账号长度不能小于3位', trigger: 'blur' }
  ],
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
      validator: (_: unknown, value: string) => {
        if (!value || value.trim() === '') {
          // 3. 如果用户名为空或空格，自动生成随机用户名
          userForm.username = generateRandomUsername()
        }
        return Promise.resolve()
      }
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能小于8位', trigger: 'blur' },
    {
      validator: (_: unknown, value: string) => {
        if (!value) return Promise.resolve()
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/
        return regex.test(value)
          ? Promise.resolve()
          : Promise.reject('密码必须包含大小写字母和数字')
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_: unknown, value: string) => {
        if (!value) return Promise.resolve()
        return value === userForm.userPassword
          ? Promise.resolve()
          : Promise.reject('两次输入的密码不一致')
      },
      trigger: 'blur'
    }
  ]
}

const handleSearch = () => {
  pagination.page = 1
  fetchUserList()
}

const handleAdd = () => {
  isEdit.value = false
  modalTitle.value = '新增用户'

  // 2. 为新增用户生成随机用户名
  const randomUsername = generateRandomUsername()

  Object.assign(userForm, {
    id: undefined,
    userAccount: '',
    username: randomUsername, // 使用随机用户名
    avatar: '',
    phone: '',
    email: '',
    gender: 0,
    userStatus: 0,
    userRole: 1,
    userPassword: '',
    confirmPassword: ''
  })

  fileList.value = []
  modalVisible.value = true
}

const handleEdit = (record: UserData) => {
  isEdit.value = true
  modalTitle.value = '编辑用户'

  // 3. 编辑用户时保留原有用户名
  Object.assign(userForm, {
    id: record.id,
    userAccount: record.userAccount,
    username: record.username, // 保留原有用户名
    avatar: record.avatar,
    phone: record.phone,
    email: record.email,
    gender: record.gender,
    userStatus: record.userStatus,
    userRole: record.userRole
  })

  if (record.avatar) {
    fileList.value = [
      {
        uid: '-1',
        name: 'avatar',
        status: 'done',
        url: record.avatar
      }
    ]
  }
  modalVisible.value = true
}

const handleDelete = async (id: number) => {
  try {
    loading.value = true
    const res = await deleteUser(id)
    if (!userForm.username) {
      userForm.username = generateRandomUsername()
    }
    if (res.data.code === 200) {
      message.success('删除成功')
      // 如果当前页只有一条数据，删除后跳转到上一页
      if (dataSource.value.length === 1 && pagination.page > 1) {
        pagination.page--
      }
      fetchUserList()
    } else {
      message.error(res.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除用户失败:', error)
    message.error('删除失败')
  } finally {
    loading.value = false
  }
}

const handleResetPassword = async (id: number) => {
  try {
    loading.value = true
    const res = await resetUserPassword(id)
    if (res.data.code === 200) {
      message.success('密码重置成功')
    } else {
      message.error(res.data.message || '密码重置失败')
    }
  } catch (error) {
    console.error('重置密码失败:', error)
    message.error('重置密码失败')
  } finally {
    loading.value = false
  }
}

const handleModalOk = async () => {
  try {
    loading.value = true
    await formRef.value?.validate()
    if (!userForm.username || userForm.username.trim() === '') {
      userForm.username = generateRandomUsername()
    }
    // 关键修复3：添加trim操作前的空值检查
    const addParams = {
      userAccount: userForm.userAccount.trim(),
      username: userForm.username.trim(),
      userPassword: userForm.userPassword?.trim(),
      avatar: userForm.avatar?.trim(),
      phone: userForm.phone.trim(),
      email: userForm.email.trim(),
      gender: userForm.gender ?? 0,
      userStatus: userForm.userStatus ?? 0,
      userRole: userForm.userRole ?? 1
    }

    if (isEdit.value) {
      if (!userForm.id) {
        message.error('用户ID不能为空')
        return
      }
      const editParams = {
        id: userForm.id,
        userAccount: userForm.userAccount.trim(),
        username: userForm.username.trim(),
        avatar: userForm.avatar?.trim(),
        phone: userForm.phone.trim(),
        email: userForm.email.trim(),
        gender: userForm.gender ?? 0,
        userStatus: userForm.userStatus ?? 0,
        userRole: userForm.userRole ?? 1
      }
      const res = await editUser(editParams)
      if (res.data.code === 200) {
        message.success('编辑成功')
        modalVisible.value = false
        fetchUserList()
      } else {
        message.error(res.data.message)
      }
    } else {
      const res = await addUser(addParams)
      if (res.data.code === 200) {
        message.success('新增成功')
        modalVisible.value = false
        fetchUserList()
      } else {
        message.error(res.data.message)
      }
    }
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}
const fetchUserList = async () => {
  try {
    loading.value = true
    const response = await getUserList({
      page: pagination.page,
      size: pagination.size,
      keyword: searchForm.keyword?.trim() || undefined
    })
    console.log('API响应:', response)
    // 关键修复4：添加组件卸载检查
    if (!isComponentMounted.value) return

    const { data } = response
    if (data.code === 200) {
      console.log(data)

      dataSource.value = data.data || []
      pagination.total = data.total || 0
      pagination.page = data.currentPage || 1
      pagination.size = data.pageSize || 10
    } else {
      message.error(data.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    message.error('获取用户列表失败')
  } finally {
    if (isMounted.value) {
      loading.value = false
    }
  }
}

const handleTableChange = (pag: TablePaginationConfig) => {
  pagination.page = pag.current || 1
  pagination.size = pag.pageSize || 10
  fetchUserList()
}

onMounted(() => {
  fetchUserList()
})
// 导航项点击事件处理
document.querySelectorAll('.nav-item').forEach(item => {
  item.addEventListener('click', function () {
    // 更新活动状态和页面标题
  })
})
</script>

<template>
  <div class="user-mgmt">
    <a-card class="search-card">
      <div class="search-form">
        <a-input
          v-model:value="searchForm.keyword"
          placeholder="请输入账号/手机号搜索"
          allowClear
          @pressEnter="handleSearch"
          @change="e => e.target.value === '' && handleSearch()"
        >
          <template #prefix>
            <SearchOutlined />
          </template>
        </a-input>
        <a-button type="primary" @click="handleSearch">搜索</a-button>
        <a-button type="primary" @click="handleAdd">
          <PlusOutlined />
          新增用户
        </a-button>
      </div>
    </a-card>

    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="{
          total: pagination.total,
          current: pagination.page,
          pageSize: pagination.size,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          showTotal: total => `共 ${total} 条`
        }"
        :loading="loading"
        row-key="id"
        @change="handleTableChange"
      >
        <template #emptyText>
          <a-empty v-if="!loading" description="暂无用户数据" />
          <div v-else style="padding: 40px 0">
            <a-spin tip="加载中..." size="large" />
          </div>
        </template>
      </a-table>
    </a-card>

    <!-- 关键修复5：将 visible 改为 open 避免警告 -->
    <a-modal
      :title="modalTitle"
      v-model:open="modalVisible"
      :confirmLoading="loading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        :model="userForm"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item name="userAccount" label="账号">
          <a-input v-model:value="userForm.userAccount" placeholder="请输入账号" />
        </a-form-item>
        <a-form-item name="username" label="用户名">
          <a-input
            v-model:value="userForm.username"
            placeholder="请输入用户名"
            @blur="
              () => {
                if (!userForm.username || userForm.username.trim() === '') {
                  userForm.username = generateRandomUsername()
                }
              }
            "
          />
        </a-form-item>
        <a-form-item name="avatar" label="头像">
          <a-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            :custom-request="customRequest"
            @change="handleChange"
          >
            <div v-if="userForm.avatar" class="avatar-preview">
              <img :src="userForm.avatar" alt="avatar" />
            </div>
            <div
              v-else
              class="avatar-preview"
              :style="{
                backgroundColor: generateAvatarColor(userForm.id || Date.now()),
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#fff',
                fontWeight: 'bold',
                fontSize: '24px',
                borderRadius: '50%'
              }"
            >
              {{ generateInitialsAvatar(userForm.username || 'U', userForm.id || Date.now()).text }}
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item name="phone" label="手机号">
          <a-input v-model:value="userForm.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item name="email" label="邮箱">
          <a-input v-model:value="userForm.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item name="gender" label="性别">
          <a-radio-group v-model:value="userForm.gender">
            <a-radio :value="0">男</a-radio>
            <a-radio :value="1">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item name="status" label="状态">
          <a-radio-group v-model:value="userForm.userStatus">
            <a-radio :value="0">启用</a-radio>
            <a-radio :value="1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item name="userRole" label="角色">
          <a-radio-group v-model:value="userForm.userRole">
            <a-radio :value="0">管理员</a-radio>
            <a-radio :value="1">普通用户</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="!isEdit"
          name="userPassword"
          label="密码"
          :rules="!isEdit ? rules.userPassword : undefined"
        >
          <a-input-password v-model:value="userForm.userPassword" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item
          v-if="!isEdit"
          name="confirmPassword"
          label="确认密码"
          :rules="!isEdit ? rules.confirmPassword : undefined"
        >
          <a-input-password v-model:value="userForm.confirmPassword" placeholder="请再次输入密码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.user-mgmt {
  padding: 0;
}
.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
}
.fixed-navbar {
  position: fixed;
  left: 0;
  top: 0;
  height: 100vh;
  width: 250px;
}
.main-content {
  margin-left: 250px; /* 等于导航栏宽度 */
}
.search-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.search-form {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-form :deep(.ant-input-affix-wrapper) {
  width: 300px;
  border-radius: 6px;
}

.search-form :deep(.ant-btn) {
  border-radius: 6px;
  height: 32px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.table-card {
  min-height: 500px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.table-actions {
  display: flex;
  gap: 12px;
}

:deep(.ant-table) {
  border-radius: 8px;
}

:deep(.ant-table-pagination) {
  margin: 16px 0;
  justify-content: flex-end;
}

:deep(.ant-avatar) {
  border: 2px solid #f0f0f0;
  transition: all 0.3s;
}

:deep(.ant-avatar:hover) {
  border-color: #006633;
}

.avatar-uploader {
  :deep(.ant-upload) {
    width: 128px;
    height: 128px;
    border-radius: 50%;
    overflow: hidden;
    border: 2px dashed #d9d9d9;
    transition: all 0.3s;
  }

  :deep(.ant-upload:hover) {
    border-color: blue;
  }

  .avatar-preview {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

:deep(.ant-modal-content) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-radio-group) {
  display: flex;
  gap: 24px;
}

:deep(.ant-input),
:deep(.ant-input-password) {
  border-radius: 6px;
}

:deep(.ant-btn) {
  border-radius: 6px;
}
@media (max-width: 768px) {
  .sidebar {
    width: 70px; /* 移动设备上缩小导航栏 */
  }

  .main-content {
    margin-left: 70px; /* 调整内容区域边距 */
  }
}
</style>
